﻿using System;
using System.Text;
using System.IO;
using WinHttp;
using System.Collections.Generic;
using System.Collections.ObjectModel;



namespace IMatrix
{
	public class Query
	{
		private const string mqlUrl = @"http://cwiprod/cwi/just_mql.jsp?user=temp&ignorePasswd=true&input=";
		public string QueryString { get; set; }		
		
		
		public Query() 
		{
		}


		/// <summary>Initializes a new <see cref="Query" /> instance with the specified <see cref=""/></summary>
		/// <param name="queryStr">The query STR.</param>
		public Query(string queryStr)
		{
			QueryString = queryStr;
		}


		/// <summary>Executes the query contained in the QueryString property.</summary>
		/// <exception cref="InvalidQueryString">Unassigned or invalid QueryString.</exception>
		public string Execute()
		{
			if (QueryString == null || QueryString.Length < 3)
			{
				throw new System.Exception("Invalid query. Must assign a value to QueryString before calling this overload.");
			}
			string resp = GetResponse();
			OutputToTxt(resp);
			return resp;
		}


		/// <summary>Executes the given query.</summary>
		/// <param name="queryStr">Query string to be executed 
		/// (QueryString property value is ignored).</param>
		public string Execute(string queryStr)
		{
			QueryString = queryStr;
			string resp = GetResponse();
			OutputToTxt(resp);
			return resp; 
		}

		/// <summary>
		/// Performs the HTTP request and retrieves the response. QueryString property value 
		/// must be assigned and is always used as the query string.
		/// </summary>
		private string GetResponse()
		{
			string resp = null;
			var oWeb = new WinHttpRequest();
			oWeb.Open("GET", mqlUrl + QueryString);
			oWeb.Send();
			resp = oWeb.ResponseText.Trim();
			return ((resp == null || resp == "" || resp.Contains("OK:") || resp.Contains("ERROR:")) ? "Err" : resp);
		}

		


		/// <summary>Outputs the response to a TXT file.</summary>
		/// <param name="outPath">The out path.</param>
		private void OutputToTxt(string responseTxt, string outPath = @"C:\Temp\IMatrixOut.txt")
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendLine("QUERYSTRING=\n" + QueryString);
			sb.AppendLine("RESPONSE=\n" + responseTxt);

			using (StreamWriter oFile = new StreamWriter(outPath)) 
			{
				oFile.Write(sb.ToString());
			}
		}

	}
}
